package com.sky.utils; /**
  * 选择了ak或使用IP白名单校验：
  */


import com.sky.properties.BaiduMapProperties;
import lombok.AllArgsConstructor;
import lombok.Data;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
@Data
@AllArgsConstructor
public class BaiduMapUtil {
    @Autowired
    private BaiduMapProperties baiduMapProperties;

//    public static final String ORIGIN = "40.066271,116.350421";
//    public static String AK = "bZyUmb9fgvNLqLTC385OUZth1WHoLGqy";
    public int getMileage(String address) throws Exception {
        //获取用户地址经纬度坐标
        Map<String,String > map = BaiduMapUtil.getGeocoderLatitude(address);
        String lng = map.get("lng").substring(0, 6);
        String lat = map.get("lat").substring(0,6);

        //获取配送距离
        Map params = new LinkedHashMap<String, String>();
        params.put("origin",baiduMapProperties.getShopOrigin());
        params.put("destination",lat+","+lng);
        params.put("ak", baiduMapProperties.getAk());

        int mileage = BaiduMapUtil.requestGetAK(params);
       return mileage;

    }

    /**
     * 获取用户的经纬度坐标
     * @param address
     * @return
     */
    public static Map<String,String> getGeocoderLatitude(String address){
        BufferedReader in = null;
        try {
            //将地址转换成utf-8的16进制
            address = URLEncoder.encode(address, "UTF-8");
            URL tirc = new URL("http://api.map.baidu.com/geocoding/v3/?address="+address+"&output=json&ak=bZyUmb9fgvNLqLTC385OUZth1WHoLGqy&callback=showLocation");

            in = new BufferedReader(new InputStreamReader(tirc.openStream(),"UTF-8"));
            String res;
            StringBuilder sb = new StringBuilder("");
            while((res = in.readLine())!=null){
                sb.append(res.trim());
            }
            String str = sb.toString();
            System.out.println("---"+str);
            Map<String,String> map = null;
            if((str != null) && (str.length() != 0)){
                int lngStart = str.indexOf("lng\":");
                int lngEnd = str.indexOf(",\"lat");
                int latEnd = str.indexOf("},\"precise");
                if(lngStart > 0 && lngEnd > 0 && latEnd > 0){
                    String lng = str.substring(lngStart+5, lngEnd);
                    String lat = str.substring(lngEnd+7, latEnd);
                    map = new HashMap<String,String>();
                    map.put("lng", lng);
                    map.put("lat", lat);
                    return map;
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 获取骑手的配送距离
     */
    /**
     * 默认ak
     * 选择了ak，使用IP白名单校验：
     * 根据您选择的AK已为您生成调用代码
     * 检测到您当前的ak设置了IP白名单校验
     * 您的IP白名单中的IP非公网IP，请设置为公网IP，否则将请求失败
     * 请在IP地址为的计算发起请求，否则将请求失败
     */
    public static int requestGetAK( Map<String, String> param) throws Exception {
         String strUrl = "https://api.map.baidu.com/directionlite/v1/riding?";
        if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
            return 0;
        }

        StringBuffer queryString = new StringBuffer();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey() + "=");
            //    第一种方式使用的 jdk 自带的转码方式  第二种方式使用的 spring 的转码方法 两种均可
            //    queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8").replace("+", "%20") + "&");
            queryString.append(UriUtils.encode((String) pair.getValue(), "UTF-8") + "&");
        }

        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        java.net.URL url = new URL(queryString.toString());
        System.out.println(queryString.toString());
        URLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuffer buffer = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        int a = 99999;
        String string = buffer.toString();
        try {
            // 解析JSON字符串
            JSONObject jsonObject = new JSONObject(string);

            // 获取result对象
            JSONObject result = jsonObject.getJSONObject("result");

            // 获取routes数组
            JSONArray routes = result.getJSONArray("routes");

            // 检查routes数组是否至少有一个元素
            if (routes.length() > 0) {
                // 获取第一个routes对象的distance值
                JSONObject firstRoute = routes.getJSONObject(0);
                int distance = firstRoute.getInt("distance");
//                System.out.println("第一个路线的距离是: " + distance + " 米");
                a=distance;
                return a;
                // 输出结果
            } else {
                System.out.println("没有找到路线");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        reader.close();
        isr.close();
        System.out.println("AK: " + buffer.toString());
        return a;
    }
}